import requests
import re
from urllib.parse import quote

import mwparserfromhell

from resolve_music_content import *

def get_final_content(pageid, max_redirects=5):
    """
    获取页面内容，自动处理重定向
    :param pageid: 初始页面ID
    :param max_redirects: 最大重定向次数(防止循环)
    :return: (最终内容, 最终pageid, 错误信息)
    """
    visited = set()  # 记录已访问的pageid防止循环
    
    while max_redirects > 0:
        if pageid in visited:
            return None, None, "检测到重定向循环"
        visited.add(pageid)
        
        # 获取页面数据（启用redirects参数让API自动处理重定向）
        url = f"https://vcpedia.cn/api.php?action=query&prop=revisions&pageids={pageid}&rvprop=content&redirects&format=json"
        response = requests.get(url)
        data = response.json()
        
        # 获取实际的页面数据（可能已重定向）
        pages = data.get('query', {}).get('pages', {})
        if not pages:
            return None, None, None, "未获取到页面数据"
        
        # 获取当前有效的pageid（可能是重定向后的新id）
        current_pageid = next(iter(pages))
        page_data = pages[current_pageid]
        
        # 检查页面是否存在
        if 'missing' in page_data:
            return None, None, None, "页面不存在"
        
        # 检查是否是重定向页面（即使API自动跳转，内容可能仍是重定向指令）
        if 'revisions' in page_data:
            title = page_data['title']
            content = page_data['revisions'][0]['*']
            if is_redirect(content):
                target = get_redirect_target(content)
                if target:
                    # 获取重定向目标的pageid
                    new_pageid = get_pageid_by_title(target)
                    if new_pageid:
                        pageid = new_pageid
                        max_redirects -= 1
                        continue
                    return None, None, None, f"无法找到重定向目标: {target}"
                return None, None, None, "无效的重定向格式"
            
            # 返回最终内容和最终pageid
            return title, content, current_pageid, None
    
    return None, None, "达到最大重定向次数"

def is_redirect(content):
    """检查是否是重定向页面"""
    return content and content.startswith(('#REDIRECT', '#redirect'))

def get_redirect_target(content):
    """从重定向内容中提取目标页面标题"""
    match = re.match(r'#REDIRECT\s*\[\[([^\]\|]+)', content, re.IGNORECASE)
    return match.group(1).strip() if match else None

def get_pageid_by_title(title):
    """根据标题获取pageid"""
    url = f"https://vcpedia.cn/api.php?action=query&titles={quote(title)}&format=json"
    response = requests.get(url)
    data = response.json()
    
    pages = data.get('query', {}).get('pages', {})
    if pages:
        pageid = next(iter(pages))
        return int(pageid) if pageid != '-1' else None
    return None

if __name__=="__main__":
    # 使用示例
    #title, content, final_pageid, error = get_final_content(2878)  # 歌曲:镜花水月
    #title, content, final_pageid, error = get_final_content(52640)  # 歌曲:独占春
    #title, content, final_pageid, error = get_final_content(3349)  # 歌曲:平行
    #title, content, final_pageid, error = get_final_content(5140)  # 歌曲:一言即中
    #title, content, final_pageid, error = get_final_content(4465)  # 歌曲:玉粽袭香
    #title, content, final_pageid, error = get_final_content(3960)  # 歌曲:我家的天空没法下雨
    title, content, final_pageid, error = get_final_content(2585)  # 歌曲:告白气球
    #title, content, final_pageid, error = get_final_content(5946)  # 歌曲:从黑暗，到光明
    #title, content, final_pageid, error = get_final_content(3987)  # 歌曲:我想在你的心脏里起舞

    #title, content, final_pageid, error = get_final_content(15030)  # 初始pageid
    
    
    if error:
        print(f"错误: {error}")
    else:
        print(f"最终pageid: {final_pageid}")
        print(f"标题: {title}")
        print(f"内容: \n{content}")
    songbox=parse_vocaloid_songbox(content)
    introduction=extract_introduction(content)
    music=parse_music_section(content)
    lyric_content=parse_lyrics_section(content)
    narrative_content=parse_narrative_section(content)
    staff_comments=parse_staff_comments(content)
    print("\n"*5+"songbox:\n")
    print(songbox)
    print("\n"*5+"introduction:\n")
    print(introduction)
    print("\n"*5+"music:\n")
    print(music)
    print("\n"*5+"lyric_content:\n")
    print(lyric_content["lyrics"])
    print("\n"*5+"staff:\n")
    print(lyric_content["staff"])
    print("\n"*5+"narrative_content:\n")#文案
    print(narrative_content)
    print("\n"*5+"staff_comments:\n")
    print(staff_comments)


    parsed = mwparserfromhell.parse(content)
    plain_text = parsed.strip_code().strip()

    print("\n"*5+"plain_text:\n")

    print(plain_text)